package tw.edu.tku.im.maze;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class UpdateGameRepParser extends PacketParser {
   public static UpdateGameRepParser INSTANCE = new UpdateGameRepParser();
   
   private UpdateGameRepParser() { }
   
   private static MazeCell[] parseCells(JSONArray jsonArray) throws JSONException {
      MazeCell[] ans = new MazeCell[jsonArray.length()];
      for(int i=0; i<jsonArray.length(); i++) {
         if(jsonArray.isNull(i)) { break; }
         ans[i] = MazeCell.parse(jsonArray.getJSONObject(i));
      }
      return ans;
   }

   @Override
   public UpdateGameRep parse(JSONObject jsonObj) throws JSONException {
      JSONObject result = jsonObj.getJSONObject("result");
      String timestamp=null;
      if(!result.isNull("timestamp")) {
         timestamp = result.getString("timestamp");
      }
      GameState gameState = GameState.parse(result.getJSONObject("gameState"));     
      if(result.isNull("mark")) {
         if(result.isNull("unmark")) {
           return new UpdateGameRep(timestamp, gameState);
         } 
         else {
            JSONArray unmarkJSONArray = result.getJSONArray("unmark");
            MazeCell[] unmark = UpdateGameRepParser.parseCells(unmarkJSONArray);
            return new UpdateGameRep(timestamp, null, unmark, gameState);
         }
      } 
      else {
         if(result.isNull("unmark")) {
            JSONArray markJSONArray = result.getJSONArray("mark");
            MazeCell[] mark = UpdateGameRepParser.parseCells(markJSONArray);
            return new UpdateGameRep(timestamp, mark, gameState);
          } 
          else {
             JSONArray markJSONArray = result.getJSONArray("mark");
             JSONArray unmarkJSONArray = result.getJSONArray("unmark");
             MazeCell[] mark = UpdateGameRepParser.parseCells(markJSONArray);
             MazeCell[] unmark = UpdateGameRepParser.parseCells(unmarkJSONArray);
             return new UpdateGameRep(timestamp, mark, unmark, gameState);
          }
      }
   }

   @Override
   public String acceptName() {
      return "updateGameResponse";
   }

}
